import urllib, cjson, os, urlparse, traceback, re, sys, string

#import configuration
from scratch_config import *

#initialize
if not os.path.exists(target_dir):
	os.mkdir(target_dir)
	print target_dir, 'is made.'

pn = 0
rn = 60
word = 'plane'
debug = False

#parse arguments
argv_len = len(sys.argv)
option = ''
try:
	for i in range(1, argv_len):
		if not sys.argv[i].startswith('-'):
			continue
		option = sys.argv[i][1:]
		if option == 'word':
			word = sys.argv[i+1]
		elif option == 'pn':
			pn = string.atoi(sys.argv[i+1])
		elif option == 'rn':
			rn = string.atoi(sys.argv[i+1])
		elif option == 'd':
			debug = True	
		else:
			print 'invalid option:', option
except:
	print 'error when parse parameter:', option	
#create url
request_url = 'http://image.baidu.com/i?ct=201326592&cl=2&lm=-1&tn=baiduimagejson&pv=&z=0&word=%s&s=0&pn=%d&rn=%d' % (word, pn, rn)
if debug:
	print request_url
#open url
result_page = urllib.urlopen(request_url)
text = result_page.read()
charset = result_page.headers.getparam('charset')
#parse results, get urls
result = cjson.decode(text)
img_urls = []
for item in result['data']:
    if item:
	img_url = item['objURL'].rstrip()
	if img_url:
    		img_urls.append(img_url)
    else:
        break
#download images
for img_url in img_urls:
    #parse filename
    file_name = img_url.split('/')[-1].split('?')[0]
    path_name = target_dir + os.sep + file_name
    print img_url
    try:
        urllib.urlretrieve(img_url, path_name)
    except:
        print 'failed to download:' + img_url
print 'over'
#quit
